﻿using System;
using System.Collections;
using System.Collections.Generic;

namespace HappyNumber
{
    class Program
    {
        //判断一个数是否是happy number(每一位的平方和最终为1)
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("请输入一个整数（输入exit退出）：");
                var writeText = Console.ReadLine();
                if (writeText == "exit")
                    break;
                var number = Convert.ToInt32(writeText);
                bool isHappyNumber = IsHappyNumber(number);
                if (isHappyNumber)
                    Console.WriteLine("输入的是一个Happy Number！");
                else
                    Console.WriteLine("输入的不是一个Happy Number！");
                Console.WriteLine();
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 计算平方和
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static int SumSquares(int number)
        {
            var dic = new ArrayList();
            while (true)
            {
                dic.Add(number % 10);
                if (number / 10 == 0)
                {
                    break;
                }

                number = number / 10;
            }
            var num = 0;
            foreach (var item in dic)
            {
                num += (int)item * (int)item;
            }
            return num;
        }

        /// <summary>
        /// 判断是否是Happy Number
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static bool IsHappyNumber(int number)
        {
            if (number != 0)
                while (true)
                {
                    if (number == 4)
                        break;
                    if (number == 1)
                        return true;
                    number = SumSquares(number);
                }
            return false;
        }
    }
}

